/*
  闪屏页以及再按一次退出
 */

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  final routerMap = {
    'login': (BuildContext context) => LoginPage()
  };

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: '/',
      routes: {
        '/': (BuildContext context) => SplashPage()
      },
      // home: HomePage() // 也可以把主页注册到路由表中
      onGenerateRoute: (RouteSettings settings) {
        // 通过路由钩子获取路由名，不在路由表中的才会回调
        // 所以我们将路由注册放到一个键值对里
        // 这样可以控制每个路由调用
        var routeName = settings.name;
        print('routeName=$routeName');
        return MaterialPageRoute(
            builder: routerMap[routeName] as Widget Function(BuildContext),
            settings: settings);
      },
      navigatorObservers: [],
    );
  }
}

class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  
  @override
  void initState() {
    super.initState();
    // 延迟三秒后跳转
    Future.delayed(Duration(seconds: 3), (){
      // 将栈中原来的对象弹出，然后入栈
      Navigator.pushReplacementNamed(context, 'login');
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.amberAccent,
        child: Center(
          child: Text('闪屏页'),
        ),
      ),
    );
  }
}

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  DateTime _lastTime = DateTime.now();

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      // onWillPop: ()=>Future.value(false),// 拦截返回键
      // onWillPop: ()=>_showExitDlg(),// 显示确认退出弹窗
      onWillPop: ()=>_tapAgain(), // 再按一次退出
      child: Scaffold(
        body: Center(
          child: Text('登录页'),
        ),
      ),
    );
  }

  Future _showExitDlg() {
    return showDialog<bool>(context: context, builder: (ctx){
      return AlertDialog(
        title: Text('退出'),
        content: Text('您确定要离开我?'),
        actions: [
          TextButton(onPressed: (){
            debugPrint('退出应用');
            // 一定要用builder传过来的上下文，
            // true表示全部出栈，即退出应用
            // false表示当前出栈, 即弹窗消失
            Navigator.pop(ctx, true);
            // exit(0);
          }, child: Text('残忍离开')),
          TextButton(onPressed: (){
            debugPrint('下次再说');
            Navigator.pop(ctx, false);
          }, child: Text('下次再说')),
        ],
      );
    });
  }

  /*
    再按一次退出
   */
  Future<bool> _tapAgain() async {
    if (DateTime.now().difference(_lastTime) > Duration(seconds: 1)) {
      _lastTime = DateTime.now();
      debugPrint('再按一次退出');
      return false;
    } else {
      return true;
    }
  }
}
